//
//  XYCustomProgressView.m
//  DrawDemo
//
//  Created by Passion on 16/3/7.
//  Copyright © 2016年 Passion. All rights reserved.
//

#import "XYCustomProgressView.h"
#import "YYNumberLabel.h"
#import "YYDisplayView.h"
#import <MJExtension.h>


#define HEX_COLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0 green:((float)((hex & 0xFF00) >> 8))/255.0 blue:((float)(hex & 0xFF))/255.0 alpha:1]
#define RGBA_COLOR(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

@interface XYCustomProgressView ()

/// 圆环背景
@property (nonatomic, strong) CAShapeLayer *backgroundLayer;
/// 圆环进度
@property (nonatomic, strong) CAShapeLayer *progressLayer;
/// 圆环阴影
@property (nonatomic, strong) CAShapeLayer *shadowLayer;
/// 数字圆
@property (nonatomic, strong) CAShapeLayer *displayLayer;


/// 圆环宽度
@property (nonatomic, assign) CGFloat circleWidth;
/// 阴影宽度
@property (nonatomic, assign) CGFloat shadowWidth;

/// 当前的值
@property(nonatomic, assign) NSInteger currentValue;


/// displayView
@property(nonatomic, weak) YYDisplayView *displayView;

@end

@implementation XYCustomProgressView

/// 进入界面时,动画时间 intervalTime
static const CGFloat loadTime = 1.5;

/// 每变化1(pm2.5) 间隔时间
static const CGFloat intervalTime = 0.02;

/// 污染等级文字

static NSString * const oneLevelStr = @"优";
static NSString * const twoLevelStr = @"良";
static NSString * const threeLevelStr = @"轻度污染";
static NSString * const fourLevelStr = @"中度污染";
static NSString * const fiveLevelStr = @"重度污染";
static NSString * const sixLevelStr = @"严重污染";

+ (instancetype)CustomProgressWithFrame:(CGRect)frame circleWidth:(CGFloat)circleWidth shadowWidth:(CGFloat)shadowWidth{
    

    return [[self alloc] initWithFrame:frame circleWidth:circleWidth shadowWidth:shadowWidth];
}

- (instancetype)initWithFrame:(CGRect)frame circleWidth:(CGFloat)circleWidth shadowWidth:(CGFloat)shadowWidth{
    
    self = [super initWithFrame:frame];
    if (self) {
        
        _circleWidth = circleWidth;
        _shadowWidth = shadowWidth;
        
        // 初始化圆弧
        [self setupCircles];
        // 初始化显示框
        [self setupdisplay];
    }
    return self;
}


#pragma mark - 初始化

- (void)setupCircles{
    
    self.backgroundColor = [UIColor clearColor];
    // 绘制圆环
    [self createCircles];
    // 设置渐变层
    [self setShadeOfBackgroundColor];
    
}

- (void)setupdisplay{
    
    // 圆弧内部的显示圆
    NSLog(@"%f",CGRectGetWidth(self.bounds));
    _displayLayer = [self createLayerWithFillColor:RGBA_COLOR( 27, 199, 15, 1) frame:CGRectMake(0, 0, CGRectGetWidth(self.bounds) - 80, CGRectGetWidth(self.bounds) - 80)];
    [self.layer addSublayer:_displayLayer];
    
    // 添加数字
    YYDisplayView *displayView = [YYDisplayView displayViewWithFrame:CGRectMake(0, 0, 100, 100)];
    displayView.center = self.center;
    _displayView = displayView;
    [self addSubview:displayView];
    
    // 设置改变颜色的block
    __weak typeof(self) weakSelf = self;
    displayView.numberLabel.changeColor = ^(pm25Level level){
        switch (level) {
            case oneLevel:{
                weakSelf.displayLayer.fillColor = RGBA_COLOR( 27, 199, 15, 1).CGColor;
                weakSelf.displayView.levelLabel.text = oneLevelStr;
                weakSelf.changeMaskColor(level);
                break;
            }
            case twoLevel:{
                weakSelf.displayLayer.fillColor = RGBA_COLOR(255, 255,  10, 1).CGColor;
                weakSelf.displayView.levelLabel.text = twoLevelStr;
                weakSelf.changeMaskColor(level);
                break;
            }
            case threeLevel:{
                weakSelf.displayLayer.fillColor = RGBA_COLOR(229, 120,  19, 1).CGColor;
                weakSelf.displayView.levelLabel.text = threeLevelStr;
                weakSelf.changeMaskColor(level);
                break;
            }
            case fourLevel:{
                weakSelf.displayLayer.fillColor = RGBA_COLOR(251,   0,   8, 1).CGColor;
                weakSelf.displayView.levelLabel.text = fourLevelStr;
                weakSelf.changeMaskColor(level);
                break;
            }
            case fiveLevel:{
                weakSelf.displayLayer.fillColor = RGBA_COLOR(134,  33,  83, 1).CGColor;
                weakSelf.displayView.levelLabel.text = fiveLevelStr;
                weakSelf.changeMaskColor(level);
                break;
            }
            case sixLevel:{
                weakSelf.displayLayer.fillColor = RGBA_COLOR(124,  54,  56, 1).CGColor;
                weakSelf.displayView.levelLabel.text = sixLevelStr;
                weakSelf.changeMaskColor(level);
                break;
            }
                
            default:
                break;
        }
    };
}

- (void)createCircles{
    
    CGFloat radius = (CGRectGetWidth(self.bounds) - _circleWidth)/2;
    
    //灰色背景圆环
    _backgroundLayer = [self createLayerWithFillColor:[UIColor clearColor] StrokeColor:HEX_COLOR(0xD5D5D5) lineWidth:_circleWidth radius:radius];
    //显示进度的圆环
    _progressLayer = [self createLayerWithFillColor:[UIColor clearColor] StrokeColor:RGBA_COLOR(27,199,15,1) lineWidth:_circleWidth radius:radius];
    _progressLayer.strokeEnd = 0;
    
    radius = (CGRectGetWidth(self.bounds) - _shadowWidth)/2 - _circleWidth;
    //圆环内部影子
    _shadowLayer = [self createLayerWithFillColor:[UIColor clearColor] StrokeColor:HEX_COLOR(0xECECEA) lineWidth:_shadowWidth radius:radius];
    
    [self.layer addSublayer:_backgroundLayer];
    [self.layer addSublayer:_progressLayer];
    [self.layer addSublayer:_shadowLayer];
}

/// 画圆
- (CAShapeLayer *)createLayerWithFillColor:(UIColor *)color frame:(CGRect)frame{
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        // 指定frame，只是为了设置宽度和高度
        circleLayer.frame = frame;
        // 设置居中显示
        circleLayer.position = self.center;
        // 设置填充颜色
        circleLayer.fillColor = color.CGColor;
        // 设置线宽
//        circleLayer.lineWidth = 2.0;
        // 设置线的颜色
//        circleLayer.strokeColor = [UIColor clearColor].CGColor;
    
        // 使用UIBezierPath创建路径
        UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:frame];
        
        // 设置CAShapeLayer与UIBezierPath关联
        circleLayer.path = circlePath.CGPath;

        return circleLayer;
}

/// 画圆弧
- (CAShapeLayer *)createLayerWithFillColor:(UIColor *)fillColor StrokeColor:(UIColor *)strokeColor lineWidth:(CGFloat)linewidth radius:(CGFloat)radius{
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.bounds = self.bounds;
    layer.anchorPoint = CGPointMake(0, 0);
    layer.lineWidth = linewidth;
    layer.fillColor = fillColor.CGColor;
    layer.strokeColor = strokeColor.CGColor;
    
    layer.lineCap = @"round";
    
    UIBezierPath *bPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) radius:radius startAngle:M_PI_4 * 3  endAngle:M_PI_2 *3 + M_PI_4 * 3 clockwise:YES];
    
    layer.path = bPath.CGPath;
    
    return layer;
}

#pragma mark - 设置渐变层 (核心代码)
/// 设置渐变层
- (void)setShadeOfBackgroundColor{

    //颜色渐变
    CALayer *colorLayer = [CALayer layer];
    colorLayer.bounds = self.bounds;
    colorLayer.position = CGPointMake(0, 0);
    colorLayer.anchorPoint = CGPointMake(0, 0);
    
    //A段 绿
    CAGradientLayer *AGradientLayer = [CAGradientLayer layer];
    AGradientLayer.bounds = CGRectMake(0, 0, CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
    AGradientLayer.position = CGPointMake(0, CGRectGetMidX(self.bounds));
    AGradientLayer.anchorPoint = CGPointMake(0, 0);
    AGradientLayer.colors = @[
                                 (__bridge id)RGBA_COLOR( 27, 199, 15, 1).CGColor,
                                 (__bridge id)RGBA_COLOR( 27, 199, 15, 1).CGColor,
//                                 (__bridge id)RGBA_COLOR(141, 227, 12, 1).CGColor,
                                 (__bridge id)RGBA_COLOR(255, 255, 10, 1).CGColor
                                 ];
    
    AGradientLayer.startPoint = CGPointMake(.2,1);
    AGradientLayer.endPoint = CGPointMake(0,0);
    
    
    AGradientLayer.locations = @[ @.25,@.8,@.95];
    //B段 金
    CAGradientLayer *BGradientLayer = [CAGradientLayer layer];
    BGradientLayer.bounds = CGRectMake(0, 0, CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
    BGradientLayer.position = CGPointMake(0, 0);
    BGradientLayer.anchorPoint = CGPointMake(0, 0);
    BGradientLayer.colors = @[
                                  (__bridge id)RGBA_COLOR(255, 255, 10, 1).CGColor,
                                  (__bridge id)RGBA_COLOR(242, 180, 15, 1).CGColor,
                                  (__bridge id)RGBA_COLOR(229, 120, 19, 1).CGColor
                                  ];
    
    BGradientLayer.startPoint = CGPointMake(0,1);
    BGradientLayer.endPoint = CGPointMake(1,0);
    BGradientLayer.locations = @[@.25,@.5,@.75];

    //C段 橙
    CAGradientLayer *CGradientLayer = [CAGradientLayer layer];
    CGradientLayer.bounds = CGRectMake(0, 0, CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
    CGradientLayer.position = CGPointMake(CGRectGetMidX(self.bounds), 0);
    CGradientLayer.anchorPoint = CGPointMake(0, 0);
    CGradientLayer.colors = @[
                                 (__bridge id)RGBA_COLOR(229, 120, 19, 1).CGColor,
                                 (__bridge id)RGBA_COLOR(240, 60,  14, 1).CGColor,
                                 (__bridge id)RGBA_COLOR(251, 0,    8, 1).CGColor,
                                 (__bridge id)RGBA_COLOR(134, 33,  83, 1).CGColor
                                 ];
    
    CGradientLayer.startPoint = CGPointMake(0,0);
    CGradientLayer.endPoint = CGPointMake(1,1);
    CGradientLayer.locations = @[@0.15,@.25,@.5,@.75];
    
    //D段 红
    CAGradientLayer *DGradientLayer = [CAGradientLayer layer];
    DGradientLayer.bounds = CGRectMake(0, 0, CGRectGetMidX(self.bounds),CGRectGetMidY(self.bounds));
    DGradientLayer.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidX(self.bounds));
    DGradientLayer.anchorPoint = CGPointMake(0, 0);
    DGradientLayer.colors = @[
                                 (__bridge id)RGBA_COLOR(134, 33,  83, 1).CGColor,
                                 (__bridge id)RGBA_COLOR(124,  54, 56, 1).CGColor,
                                 (__bridge id)RGBA_COLOR(124,  54, 56, 1).CGColor,
                                 ];
    
    DGradientLayer.startPoint = CGPointMake(1,0);
    DGradientLayer.endPoint = CGPointMake(0,1);
    DGradientLayer.locations = @[@0.1,@0.2,@0.7];
    
    [colorLayer addSublayer:AGradientLayer];
    [colorLayer addSublayer:BGradientLayer];
    [colorLayer addSublayer:CGradientLayer];
    [colorLayer addSublayer:DGradientLayer];
    
    [self.layer addSublayer:colorLayer];
    colorLayer.mask = _progressLayer;
}

#pragma mark - 辅助部分

/// 白色分割线 (未用到)
- (void)equalPartsOfCircle:(NSInteger)count{

    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [[UIColor whiteColor] setFill];
    //白色分割线
    CGContextTranslateCTM(context, self.bounds.size.width/2, self.bounds.size.height/2);
    for (int i = 0; i < count; i ++) {
        CGContextAddRect(context, CGRectMake(0, -CGRectGetHeight(self.bounds)/2, 2, _circleWidth));
        CGContextFillPath(context);
        CGContextRotateCTM(context, 2*M_PI/count);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.layer addSublayer:imageView.layer];

}

/// 辅助线条
- (void)line:(NSInteger)count{
    
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [[UIColor blackColor] setFill];
    
    //白色分割线
    CGContextTranslateCTM(context, self.bounds.size.width/2, self.bounds.size.height/2);
    for (int i = 0; i < count; i ++) {
        CGContextAddRect(context, CGRectMake(0, -CGRectGetHeight(self.bounds)/2, 2, _circleWidth));
        CGContextFillPath(context);
        CGContextRotateCTM(context, 2*M_PI/count);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.layer addSublayer:imageView.layer];
    
}


#pragma mark - 接口 用于控制圆环进度

/// 动画从 0 到 percent
-(void)setPercent:(NSInteger)percent
{
    // 限定范围
    if (percent > 999 ) {
        percent = 999;
    }else if (percent < 1){
        percent = 1;
    }
    
    // 圆环动画
    [self setPercentOldValue:0 newValue:[self pm25ToNumber:percent] duration:loadTime];
    
    // 值动画
//    self.displayView.numberLabel.text = [NSString stringWithFormat:@"%li",percent];
    [self.displayView setNumber:percent oldNumber:0 duration:loadTime];
    
    //保存当前值
    self.currentValue = percent;
}

/// 动画从 old 到 new
-(void)setPercentNewValue:(NSInteger)newValue
{
    // 限定范围
    if (newValue > 999 ) {
        newValue = 999;
    }else if (newValue < 1){
        newValue = 1;
    }

    
    CGFloat animTime = ABS((newValue - self.currentValue) * intervalTime);

    if (animTime < 0.7) {
        animTime = 0.7;
    }else if(animTime > 2.0){
        animTime = 2.0;
    }
    
    // 圆环动画
    [self setPercentOldValue:[self pm25ToNumber:self.currentValue] newValue:[self pm25ToNumber:newValue] duration:animTime];
    // 值动画
    [self.displayView setNumber:newValue oldNumber:self.currentValue duration:animTime];
    //保存当前值
    self.currentValue = newValue;

}


/// 进度从 old 到 new ,时长 duration
-(void)setPercentOldValue:(CGFloat)oldValue newValue:(CGFloat)newValue duration:(CFTimeInterval)duration{
    
    // 圆环动画
    CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    basic.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    basic.duration = duration;
    basic.fromValue = @(oldValue * 0.01);
    basic.toValue = @(newValue * 0.01);
    basic.removedOnCompletion = NO;//动画执行完成后不删除动画
    // 设置圆角
    basic.fillMode = @"forwards";
    [_progressLayer addAnimation:basic forKey:nil];
}


#pragma mark - 将pm25的值转化为圆环对应的进度
//#define PM_N1 (4.0/9.0)   //第一部分的值
//#define PM_N2 (1.0/6.0)   //第二部分的值
//#define PM_N3 (1.0/45.0)   //第三部分的值
/// 将pm25的值转换成进度条中的浮点数字
-(CGFloat)pm25ToNumber:(NSInteger)pm25{
    
    if (pm25 > 1000) pm25 = 1000;
    if (pm25 < 1) pm25 = 1;
    
    static const CGFloat n1 = 4.0/9.0;      //第一部分的比例系数
    static const CGFloat n2 = 1.0/6.0;      //第二部分的比例系数
    static const CGFloat n3 = 1.0/45.0;     //第三部分的比例系数
    
    CGFloat pm_25 = (CGFloat)pm25;
    CGFloat number = 0;
    
    if(pm25 > 250 )
    {
        number = n3 * (pm_25 - 250) + n2 * 100 + n1 * 150;
    }
    else if(pm25 > 150)
    {
        number = n2 * (pm_25 - 150) + n1 * 150;
    }
    else
    {
        number = n1 * pm_25;
    }
    
    return number;
}

/*
 圆环的总度数 360 - 45 = 315度
 分为 3部分,
 第一部分pm2.5的间隔是1,范围 : 45度 ~ 45+180度.(圆的底部中点为0度,圆环的其实位置为45度),
 对应的PM2.5范围  : 0 ~ 150.
 pm2.5 每增加1 ,度数增加 180/150 ,值增加 (180/150) * (100/270) = 4/9 = 0.44444
 
 第二部分pm2.5的间隔是x,范围 : 45+180度 ~ 45+180+45 度.
 对应的PM2.5范围  : 150 ~ 250.
 pm2.5 每增加1 ,度数增加 45/100 ,值增加 (45/100) * (100/270) = 1/6 = 0.1666666
 
 第三部分pm2.5的间隔是x,范围 : 45+180+45度 ~ 45+180+45+45 度.
 对应的PM2.5范围  : 250 ~ 1000.
 pm2.5 每增加1 ,度数增加 45/750 ,值增加 (45/750) * (100/270) = 1/45 = 0.02222
 */

#pragma mark - 销毁

- (void)dealloc{

}
@end
